import json
import logging
from typing import Dict, Any
from config import get_mirror_conn
from datetime import datetime


# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('message_processor')

class MessageProcessor:
    """消息处理类"""
    
    @staticmethod
    def process_task_message(body: bytes) -> None:
        """处理任务消息"""
        try:
            # 解析 JSON 消息
            message = json.loads(body.decode('utf-8'))
            logger.info(f"收到任务消息: {message}")
            
            # 处理任务
            task_data = message
            result = MessageProcessor._process_calculation(task_data)
            logger.info(f"计算任务结果: {result}")
            # 处理成功
            
        except json.JSONDecodeError:
            logger.error(f"无效的 JSON 消息: {body[:100]}...")
        except Exception as e:
            logger.error(f"处理消息时发生错误: {e}")
    
    @staticmethod
    def _process_calculation(data: Dict[str, Any]) -> str:
        logger.info(f"事情不简单: {data}")
        MessageProcessor._save(data)
        return data
    
    @staticmethod
    def _send_notification(data: Dict[str, Any]) -> None:
        """发送通知"""
        # 模拟发送通知
        recipient = data.get('recipient')
        message = data.get('message')
        
        logger.info(f"模拟发送通知给 {recipient}: {message}")

    @staticmethod
    def _save(params):
        db_conn = get_mirror_conn()
        if params:
            data = MessageProcessor._get_data(params)
            logger.info(f"插入数据: {data}")
            db_conn.insert('gather_record_copy1', data)

    @staticmethod
    def _get_data(param):
        result = ""
        if param:
            result = {
                'uip': param.get("ip"),
                'sip': param['uip'],
                'url': param.get("url"),
                'evname': param.get("e"),
                'time': datetime.now(),
                "ua": param.get("ua"),
                'target':param.get("tg"),
                'content':  param.get("c") if param.get("c") else "",
                'host':param.get("st"),
                'uid': param.get("spid") if param.get("spid") else (param.get("uid") if param.get("uid") else "no_usr_key"),
                "page": param.get('pg'),
                "pos": (param.get("x") if param.get("x") else "0") + "/" + (param.get("y") if param.get("y") else "0"),
                "clt": ""
            }
        return result

